const pay = require("../db/pay");
const _ = require("lodash");
const { alipaySdk } = require("../config/index");
const config = require("../config/index");

async function payment({
  out_trade_no,
  subject,
  total_amount,
  goods_detail,
  returnUrl,
}) {
  const bizContent = {
    out_trade_no,
    product_code: "QUICK_WAP_WAY",
    subject,
    total_amount,
  };
  console.log("bizContent", bizContent);
  const url = await alipaySdk.pageExec("alipay.trade.wap.pay", {
    method: "GET",
    bizContent,
    returnUrl,
  });
  return url;
}

exports.placeOrder = async function (ctx) {
  ctx.verifyParams({
    createTime: "datetime",
    goods: "array",
    totalPrice: "number",
    address: "object",
  });
  const uid = ctx.state.user.id;
  const data = _.cloneDeep(ctx.request.body);
  data.goods = JSON.stringify(data.goods);
  data.address = JSON.stringify(data.address);
  try {
    const result = await pay.addOrderList({ uid, ...data, state: 1 });
    // insertId
    if (result.affectedRows) {
      const order = await pay.getOrderById({ id: result.insertId });
      ctx.body = {
        code: 200,
        message: "下单成功",
        data: order,
      };
    } else {
      ctx.body = {
        code: 400,
        message: "下单失败",
      };
    }
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 400,
      message: "数据库操作失败",
      error,
    };
  }
};

exports.order = async function (ctx) {
  const uid = ctx.state.user.id;
  const state = +ctx.request.query.state;
  try {
    const result = await pay.order({ uid, state });
    ctx.body = {
      code: 200,
      message: "订单查询成功",
      data: result,
    };
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "数据库报错",
      error: error,
    };
  }
};

exports.orderCount = async function (ctx) {
  const uid = ctx.state.user.id;

  try {
    const result = await pay.getOrderCount({ uid });
    ctx.body = {
      code: 200,
      message: "订单查询成功",
      data: result,
    };
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "数据库报错",
      error: error,
    };
  }
};

exports.payment = async function (ctx) {
  ctx.verifyParams({
    id: "string",
    returnUrl: "string",
  });
  const { id, returnUrl } = ctx.request.body;
  const order = await pay.getOrderById({ id: id });
  if (order.length) {
    const data = order[0];
    try {
      const result = await payment({
        out_trade_no: data.id,
        subject: "商品",
        total_amount: data.totalPrice,
        goods_detail: data.goods,
        returnUrl,
      });

      ctx.body = {
        code: 200,
        message: "发起支付成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 400,
        message: "发起支付失败",
        error: error,
      };
    }
  } else {
    //
    ctx.body = {
      code: 400,
      message: "订单不存在",
    };
  }
};

exports.orderDelete = async function (ctx) {
  ctx.verifyParams({
    id: "string",
  });
  const id = ctx.request.query.id;
  const uid = ctx.state.user.id;
  // deleteOrder
  const result = await pay.deleteOrder({ id, uid });
  if (result.affectedRows) {
    ctx.body = {
      code: 200,
      message: "删除成功",
    };
  } else {
    ctx.body = {
      code: 400,
      message: "订单不存在或没有权限",
    };
  }
};

exports.query = async function (ctx) {
  ctx.verifyParams({
    out_trade_no: "string",
  });
  const { out_trade_no } = ctx.request.query;
  try {
    const result = await alipaySdk.exec("alipay.trade.query", {
      bizContent: {
        out_trade_no,
      },
    });
    if (result.code === "10000") {
      const s = await pay.editOrder({ id: out_trade_no, state: 2 });
      if (s.affectedRows) {
        ctx.body = {
          code: 200,
          message: "支付成功",
        };
      } else {
        ctx.body = {
          code: 200,
          message: "支付成功, 订单状态未改变",
        };
      }
    } else {
      ctx.body = {
        code: 404,
        message: "订单支付中, 当前未查询到支付",
      };
    }
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "支付参数参数不正确",
    };
  }
};

// http://olmt.iq/tody?charset=utf-8&out_trade_no=46&method=alipay.trade.wap.pay.return&total_amount=74.00&sign=OIVKwVZ1ubM52C%2FpCptWwmT4ZtEcM0uNsnb9A%2B10oAhKSF7PyH6ff8BCpLcnpw22zzQqyZpcbse9eWjMDE%2B9X6dZbqrf7v2cuWgfCbHqxkVNASCUw%2Bcz%2Bbjmjeh4eUp2ZzTHWzBulVFVHEhefbrqab6lPQVXGhZVTHnOL2GHL5N6yVUH6V8rpyG89pC1vEHjLxDaIdrZHqdW5ZyaDt%2F5RIehqjbl2TYNa7D05iHmhXSjdf0%2BrMkRXRxretgevbsFNPDXWFz8yF6eBkaPJvIpUvb6K%2BzMmnfurnH%2F%2F47OlBa1mkc8TjUsNesVn9XPd95npjEtuJn7bh58s9HvyfT95w%3D%3D&trade_no=2024102922001468500504692043&auth_app_id=9021000133628166&version=1.0&app_id=9021000133628166&sign_type=RSA2&seller_id=2088721025496321&timestamp=2024-10-29+13%3A19%3A25

// https://www.baidu.com/?charset=utf-8&out_trade_no=13&method=alipay.trade.wap.pay.return&total_amount=23.00&sign=yCGnsgxUKKdRAHYvVTG7GsXVLUIj%2FKuVSW%2FDHGer7L%2BrCkG82CFxYdU%2FaboaUGlQKXTDIwNsWgKYoayMM3LGkFwdzc9dbcHtQs16BuOvGBuZqprlpWED6%2FqisMEoum5HQengQZpTF5myh8lUBRnGde%2BzERvMF5I8yNJ3GQqfwx2WZvfJdyBfQufbM7dCbmtijuvsUUa6sZzw39Gd0bpiCLkvOGWzgQclkcvo9HWIv8qYn3W%2BCAnEl2aB4sMIRJXCucwKduVr31bT4U7ZfUVmVhZuGQO4ya4f6r7AJeP3jZwAlcl%2Bdc1qo%2FJ8%2Far3lLDJb0abEZQYfv35aKfFZuYL6g%3D%3D&trade_no=2024102922001468500504692044&auth_app_id=9021000133628166&version=1.0&app_id=9021000133628166&sign_type=RSA2&seller_id=2088721025496321&timestamp=2024-10-29+13%3A27%3A56

// {
//   "msg": "Business Failed",
//   "code": "40004",
//   "outTradeNo": "13",
//   "subMsg": "交易不存在",
//   "subCode": "ACQ.TRADE_NOT_EXIST",
//   "receiptAmount": "0.00",
//   "pointAmount": "0.00",
//   "buyerPayAmount": "0.00",
//   "invoiceAmount": "0.00"
// }

// {
//   "code": "10000",
//   "msg": "Success",
//   "buyerLogonId": "qck***@sandbox.com",
//   "buyerPayAmount": "0.00",
//   "buyerUserId": "2088722025568502",
//   "buyerUserType": "PRIVATE",
//   "invoiceAmount": "0.00",
//   "outTradeNo": "13",
//   "pointAmount": "0.00",
//   "receiptAmount": "0.00",
//   "sendPayDate": "2024-10-29 13:27:53",
//   "totalAmount": "23.00",
//   "tradeNo": "2024102922001468500504692044",
//   "tradeStatus": "TRADE_SUCCESS"
// }
